<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Admin;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Authentication\AuthenticationService;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module
{

    public function onBootstrap( MvcEvent $e )
    {
        $e->getApplication()->getServiceManager()->get( 'translator' );
        $e->getApplication()->getServiceManager()->get( 'viewhelpermanager' )->setFactory( 'javascript', function($sm) use ($e) {
            $viewHelper = new \Application\View\Helper\Javascript( $e->getRouteMatch() );
            return $viewHelper;
} );
        $e->getApplication()->getServiceManager()->get( 'viewhelpermanager' )->setFactory( 'grid', function($sm) use ($e) {
            $viewHelper = new \Admin\View\Helper\Grid();
            return $viewHelper;
} );
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach( $eventManager );
        $eventManager->attach( 'route', array($this, 'checkUserAuth'), 2 );
        $this->initAcl( $e );
        $e->getApplication()->getEventManager()->attach( 'route', array($this, 'checkAcl') );

    }

    public function checkUserAuth( MvcEvent $e )
    {
        $router       = $e->getRouter();
        $matchedRoute = $router->match( $e->getRequest() );

//this is a whitelist for routes that are allowed without authentication
//!!! Your authentication route must be whitelisted
        $allowedRoutesConfig = array('', 'acesso', 'application', 'login');
        $request             = $e->getRequest();

        if ($request->isXmlHttpRequest()) {
            return;
        }
        if (!isset( $matchedRoute ) || in_array( $matchedRoute->getMatchedRouteName(), $allowedRoutesConfig )) {
// no auth check required
            return;
        }

//if is ajax
        $identity = new AuthenticationService();
        if (!$identity->getIdentity()) {
//redirect to login route...
            $response = $e->getResponse();
            $response->setStatusCode( 302 );
//this is the login screen redirection url
            $url      = $e->getRequest()->getBaseUrl() . '/acesso';
            $response->getHeaders()->addHeaderLine( 'Location', $url );
            $app      = $e->getTarget();
//dont do anything other - just finish here
            $app->getEventManager()->trigger( MvcEvent::EVENT_FINISH, $e );
            $e->stopPropagation();
        }

    }

    public function initAcl( MvcEvent $e )
    {

        $acl   = new \Zend\Permissions\Acl\Acl();
        $roles = array(
            'guest' => array(
                'home',
                'login',
                'register'
            ),
            'admin' => array(
                'admin',
                'listar',
                'novo',
                'editar',
                'salvar',
                'report',
                'deletar'
            ),
        );

        $allResources = array();
        foreach ($roles as $role => $resources) {

            $role = new \Zend\Permissions\Acl\Role\GenericRole( $role );
            $acl->addRole( $role );

            $allResources = array_merge( $resources, $allResources );

//adding resources
            foreach ($resources as $resource) {
// Edit 4
                if (!$acl->hasResource( $resource ))
                    $acl->addResource( new \Zend\Permissions\Acl\Resource\GenericResource( $resource ) );
            }
//adding restrictions
            foreach ($allResources as $resource) {
                $acl->allow( $role, $resource );
            }
        }
//testing
//var_dump($acl->isAllowed('admin','home'));
//true
//setting to view
        $e->getViewModel()->acl = $acl;

    }

    public function checkAcl( MvcEvent $e )
    {
        $route    = $e->getRouteMatch()->getMatchedRouteName();
//you set your role
        $userRole = 'admin';
       
        if (!$e->getViewModel()->acl->isAllowed( $userRole, $route )) {
           die('bvbvbv');
            /* $response = $e->getResponse();
              }
              //location to page or what ever
              $response->getHeaders()->addHeaderLine( 'Location', $e->getRequest()->getBaseUrl() . '/404' );
              $response->setStatusCode( 404 ); */
        }

    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';

    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );

    }

    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'db' => function ($sm) {
                    $dbAdapter = $sm->get( 'Zend\Db\Adapter\Adapter' );
                    return $dbAdapter;
  }
            )
        );

    }

}
